package io.xccit.train.common.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import io.xccit.train.common.context.MemberLoginContext;
import io.xccit.train.common.util.JwtUtil;
import io.xccit.train.model.member.domain.vo.MemberVO;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author CH_ywx
 * @version 1.0
 * @create 2024/11/13
 * <p>会员登录拦截器</p>
 */
@Component
public class MemberInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 前置拦截器
     * @param request 请求
     * @param response 响应
     * @param handler 处理器
     * @return 处理结果
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (StrUtil.isNotBlank(token)){
            JSONObject loginMember = jwtUtil.getJsonObject(token);
            MemberLoginContext.setMember(JSONUtil.toBean(loginMember, MemberVO.class));
        }
        return true;
    }
}
